package cn.wolfcode.luowowo.website.web.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor {
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = CookieUtils.getToken(request);
        UserInfo userInfo = userInfoRedisService.getUserByToken(token);
        //1.获取请求路径的映射方法
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            //2.判断是否含有@RequireLogin注解
            if (hm.hasMethodAnnotation(RequireLogin.class)) {
                //3.如果有, 则判断当前用户是否登录
                //4.如果已登录, 放行, 否则返回false;
                if (userInfo == null) {
                    // 延长cookie时长
                    CookieUtils.addCookie("token", token, RedisKeys.LOGIN_TOKEN.getTime().intValue(), response);
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        request.getSession().setAttribute("userInfo",userInfo);
        return true;
    }
}
